var express = require('express');
var router = express.Router();
const { userModel, addressListModel, flowerModel, storeModel, orderModel } = require('../model/model')
const { alipaySdk, alipaySdk1 } = require('./alipaySdk')
const { AlipayFormData } = require('alipay-sdk')
const axios = require('axios')
const Core = require('@alicloud/pop-core');

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

// 获取用户数据
router.get('/getUser', async (req, res) => {
  let data = await userModel.find()
  res.send({
    code: "200",
    message: 'success',
    data
  })
})

// 添加用户数据
router.post('/addUser', async (req, res) => {
  console.log(req.body);
  await userModel.create(req.body)
  res.send({
    code: "200",
    message: 'success'
  })
})


//添加收货地址


router.post("/address", async (req, res) => {
  let { userId } = req.query
  let userList = await userModel.findOne({ _id: userId })
  let data
  if (req.body.isdefault) {
      let addlist = userList.address
    await addressListModel.updateMany({ _id:addlist }, { isdefault: false })
  }
  await addressListModel.create(req.body)
  data = await addressListModel.find()
  userList.address.push(data[data.length - 1]._id)
  await userModel.updateOne({ _id: userId }, { address: userList.address })

  res.send({
    code: 200
  })
})

//获取收货地址

router.get("/address", async (req, res) => {
  let { userId } = req.query
  let userList = await userModel.findOne({ _id: userId })
  let data = await addressListModel.find({_id:userList.address})
  res.send({
    code: 200,
    data
  })
})



//修改默认收货地址
router.put("/address", async (req, res) => {
  let {ids,userId} = req.query
  let userList = await userModel.findOne({ _id: userId })
  await addressListModel.updateMany({ _id:userList.address }, { isdefault: false })
  await addressListModel.updateOne({ _id: ids }, { isdefault: true })
  res.send({
    code: 200
  })
})


// 支付宝
router.post('/payment', async (req, res) => {
  const { order_id, name, price, user, pid } = req.body
  // console.log(user._id);

  const bizContent = {
    out_trade_no: order_id, // 商户网站唯一订单号
    product_code: "FAST_INSTANT_TRADE_PAY", // 销售产品码，与支付宝签约的产品码名称
    total_amount: price, // 交易金额（单位: 元 保留小数点后两位）
    subject: name, // 交易的标题/交易描述
  }
  //alipay.trade.wap.pay
  //alipay.trade.query
  let url = null
  if (name === '支付宝支付') {
    url = alipaySdk.pageExec('alipay.trade.wap.pay', 'GET', { bizContent, returnUrl: `http://localhost:5173/orderform?cate=2` })
    await orderModel.updateOne({ _id: pid }, { state: 2 })

  } else {
    url = alipaySdk.pageExec('alipay.trade.wap.pay', 'GET', { bizContent, returnUrl: `http://localhost:5173/orderSuccess/${user._id}` })
  }
  res.send({
    code: 200,
    data: url
  })
})

// 根据id获取用户数据
router.post('/getUserById', async (req, res) => {
  let { _id } = req.body
  console.log(_id, 'id11111111111111111111111');

  const user = await userModel.findOne({ _id: _id })
  res.send({
    code: 200,
    data: user
  })
})

// 支付状态
router.post('/getSuccess', async (req, res) => {
  let { timestamp, total_amount, id, out_trade_no } = req.body.data
  // console.log(data.timestamp,'付款时间');
  // console.log(data.total_amount,'支付金额');
  // console.log(data.id,'登录用户id');
  // console.log(data.out_trade_no,'订单编号');

  let obj = await userModel.findOne({ _id: id })
  let isShow = obj.wallet.wallethandler.find(item => item.out_trade_no == out_trade_no)
  console.log(isShow, '111111111111111111111');

  // 进行添加字符
  if (!isShow) {
    obj.wallet.wallethandler.unshift({ time: timestamp, price: total_amount, out_trade_no, status: '+', type: '充值' })
    obj.wallet.remaining = Number(obj.wallet.remaining) + Number(total_amount)
  }

  let success = await userModel.updateOne({ _id: id }, { wallet: obj.wallet })
  // console.log(obj.wallet.wallethandler);


  res.send({
    code: '200',
    msg: '充值成功'
  })
})

// 创建 Client 对象
const client = new Core({
  accessKeyId: 'LTAI5tJZznCn3CBpKRYteCWo', // 替换成自己的 AccessKey ID
  accessKeySecret: 'jFIJ3aBW8jSUnllSaY97K6Xlch0dSm', // 替换成自己的 AccessKey Secret
  endpoint: 'https://dysmsapi.aliyuncs.com', // API 访问入口，根据实际情况修改
  apiVersion: '2017-05-25' // API 版本号，根据实际情况修改
});
let yanzhengma = '1111'
// 生成随机验证码
function generateCode() {
  const code = Math.floor(Math.random() * (9999 - 1000 + 1)) + 1000;
  // yanzhengma = code.toString()
  return code.toString();
}

// 发送短信验证码
router.post('/SmsRequest', (req, res) => {
  const phoneNumber = req.body.phone; // 获取手机号码
  // console.log(phoneNumber,'SmsRequest-----------------------------');

  const code = generateCode(); // 生成验证码
  yanzhengma = code // 找回密码的校验，yanzhengma存储的是生成的验证码
  const params = {
    "RegionId": "cn-hangzhou", // 短信服务所在区域，可以参考阿里云文档
    "PhoneNumbers": phoneNumber, // 目标手机号码
    "SignName": "巨象开发", // 短信签名名称，需先在阿里云控制台中申请审核通过
    "TemplateCode": "SMS_474825358", // 短信模板 CODE，需先在阿里云控制台中申请审核通过
    "TemplateParam": JSON.stringify({ // 短信模板参数，为 JSON 字符串格式
      "code": code // 模板中的变量名和对应的值
    })
  };

  const requestOption = { // 设置请求超时时间等选项
    method: 'POST',
    timeout: 5000
  };
  // 调用 SendSms 方法发送短信
  client.request('SendSms', params, requestOption).then((result) => {
    console.log(result); // 打印发送结果

    res.status(200).json({ // 返回状态码和生成的验证码
      message: '验证码已发送，请注意查收！',
      // code: code // 返回验证码
    });
  }, (ex) => {
    console.log(ex); // 打印异常信息

    res.status(500).json({ // 返回错误状态码和错误信息
      message: '短信发送失败，请稍后重试！'
    });
  });
});

// 验证码验证
router.post('/verify', (req, res) => {
  // const phoneNumber = req.body.phoneNumber; // 获取手机号码
  const inputCode = req.body.code; // 获取用户输入的验证码
  const generatedCode = yanzhengma; // 获取之前生成的验证码
  if (inputCode === generatedCode && inputCode !== '' && generatedCode !== '') { // 验证码一致，登录成功
    res.send({
      code: 200,
      message: '验证成功！'
    });
  } else { // 验证码不一致，登录失败
    res.send({
      code: 201,
      message: '验证码错误，请重新输入！'
    });
  }
});


// 再次验证

router.post('/reverifyCode', async (req, res) => {
  const { code } = req.body
  if (code === yanzhengma) {
    res.send({
      code: 200
    })
  } else {
    res.send({
      code: 301
    })
  }
})

// 当密码验证成功后进行修改支付密码
router.post('/setPayPwd', async (req, res) => {
  const { newPwd, _id } = req.body
  let obj = await userModel.findOne({ _id })
  if (obj) {
    await userModel.updateOne({ _id }, { paypassword: newPwd })
    res.send({
      code: 200,
      msg: '修改成功'
    })
  } else {
    res.send({
      code: 301,
      msg: '修改失败'
    })
  }
})


// 获取用户密码是否设置

router.get('/isSetPayPwd', async (req, res) => {
  const { _id } = req.query
  let user = await userModel.findOne({ _id })
  console.log(user);

  if (user.paypassword.length > 2) {
    // 代表已经设置
    res.send({
      code: 200,
      msg: '已经设置密码'
    })
  } else {
    // 未设置
    res.send({
      code: 301,
      msg: '未设置密码'
    })
  }
})


// 进行付款

router.post('/VerifyPwd', async (req, res) => {
  const { _id, pwd, out_trade_no, total_amount, pid } = req.body
  console.log(_id, pwd, out_trade_no, total_amount, pid);


  let result = await orderModel.updateOne({ _id: pid }, { state: 2 })
  let user = await userModel.findOne({ _id: _id, paypassword: pwd })
  let isShow = user.wallet.wallethandler.find(item => item.out_trade_no == out_trade_no)
  // 添加支付记录
  if (!isShow) {
    user.wallet.wallethandler.unshift({ time: new Date().toLocaleString(), price: total_amount, out_trade_no, status: '-', type: '付款' })
    user.wallet.remaining = Number(user.wallet.remaining) - Number(total_amount)
  }
  await userModel.updateOne({ _id: _id }, { wallet: user.wallet })

  if (user) {


    res.send({
      code: 200,
      msg: '密码正确'
    })
  } else {
    res.send({
      code: 400,
      msg: '密码错误'
    })
  }
})







// 删除地址
router.delete("/address", async (req, res) => {
  let { ids, userId } = req.query
  let userList = await userModel.findOne({ _id: userId })
  let addressList = userList.address
  let index = addressList.findIndex(item => item == ids)
  addressList.splice(index, 1)
  await userModel.updateOne({ _id: userId }, { address: addressList })
  await addressListModel.deleteOne({ _id: ids })
  res.send({
    code: 200
  })
})

// 获取编辑时的地址
router.get("/upaddress", async (req, res) => {
  let { ids } = req.query
  let data = await addressListModel.findOne({ _id: ids })

  res.send({
    code: 200,
    data: data
  })
})
// 修改地址
router.put("/upress", async (req, res) => {
  let { ids,userId } = req.query
  if (req.body.isdefault) {
    let userList = await userModel.findOne({ _id: userId })
    await addressListModel.updateMany({ _id:userList.address }, { isdefault: false })
  }

  await addressListModel.updateOne({ _id: ids }, req.body)
  res.send({
    code: 200
  })
})


// 修改支付密码

router.post('/ChangePayPwd', async (req, res) => {
  const { _id, pwd, val1 } = req.body

  let user = await userModel.findOne({ _id, paypassword: pwd })


  if (user) {
    // 表示原密码输入正确
    await userModel.updateOne({ _id}, { paypassword: val1 })
    res.send({
      code: 200,
      msg: '修改成功'
    })
  } else {
    // 表示原密码输入错误
    res.send({
      code: 301,
      msg: '原密码输入错误'
    })
  }

})




//获取收藏商品
router.get("/collect", async (req, res) => {
  let { userId, tab } = req.query
  let userList = await userModel.findOne({ _id: userId })
  let data = null
  if (tab == 0) {
    data = await flowerModel.find({ _id: userList.collect })
  }
  else {
    data = await storeModel.find({ _id: userList.store })
  }
  res.send({
    code: 200,
    data
  })
})

//删除收藏商品
router.delete('/collect', async (req, res) => {
  let { userId, tab } = req.query
  let ids = req.query.ids.split(',')
  let userList = await userModel.findOne({ _id: userId })
  if (tab == 0) {
    ids.forEach(item => {
      let index = userList.collect.findIndex(t => t == item)
      userList.collect.splice(index, 1)
    })
    await userModel.updateOne({ _id: userId }, { collect: userList.collect })
  }
  else {
    ids.forEach(item => {
      let index = userList.store.findIndex(t => t == item)
      userList.store.splice(index, 1)
    })
    await userModel.updateOne({ _id: userId }, { store: userList.store })
  }
  res.send({
    code: 200
  })
})

//获取商品订单
router.get("/order", async (req, res) => {
  let { cate } = req.query
  let order = orderModel.find()
  if (cate == 0) {
    order = order.find()
  }
  else {
    order = order.find({ state: cate })
  }
  order = await order.find()
  res.send({
    code: 200,
    order
  })
})

//获取订单详情
router.get("/order_details", async (req, res) => {
  let { ids } = req.query
  let data = await orderModel.findOne({ _id: ids })
  res.send({
    code: 200,
    data
  })
})

//获取该订单的商家信息
router.get("/store", async (req, res) => {
  let { ids } = req.query
  let data = await storeModel.findOne({ _id: ids })
  res.send({
    code: 200,
    data
  })
})

//取消订单
router.delete("/order",async (req,res)=>{
  let {ids} = req.query
  await orderModel.deleteOne({_id:ids})
  res.send({
    code:200
  })
})

module.exports = router

